package com.archgeek.rpc.thrfit;

import com.archgeek.rpc.thrfit.gen.StudentService;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * @author pizhihui
 * @date 2022-04-07 10:49
 */
public class ClientFactory extends BasePooledObjectFactory<StudentService.Client> {

    private String host;
    private int port;

    public ClientFactory(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public StudentService.Client create() throws Exception {

        TTransport transport = new TSocket(host, port);
        try {
            transport.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        TBinaryProtocol protocol = new TBinaryProtocol(transport);

        StudentService.Client client = new StudentService.Client(protocol);

        System.out.println("创建客户端......" + client);
        return client;
    }

    @Override
    public PooledObject<StudentService.Client> wrap(StudentService.Client obj) {
        return new DefaultPooledObject<>(obj);
    }

    @Override
    public boolean validateObject(PooledObject<StudentService.Client> p) {
        return p.getObject().getOutputProtocol().getTransport().isOpen();
    }

//    @Override
//    public void passivateObject(PooledObject<StudentService.Client> p) throws Exception {
//        p.getObject().getOutputProtocol().getTransport().flush();
//        p.getObject().getOutputProtocol().getTransport().close();
//    }
}
